package com.heima.aliyun.green.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.green.model.v20180509.ImageSyncScanRequest;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.HttpResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.heima.aliyun.green.uploader.ClientUploader;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/***
 * 图片审核
 */
public class ImageGreenScan {

    @Autowired
    private AliyunProperties aliyunProperties;

    /***
     * 图片检测
     * 该方法需要传入图片路径集合
     * @throws Exception
     */
    public Map<String, String> imageGreenScanForUrl(List<String> iamgeList) {
        //1、client创建
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                aliyunProperties.getAccessKey(),
                aliyunProperties.getSecret());
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        //2、将本地图片上传至阿里云
        List<JSONObject> taskList = new ArrayList<>();
        for (String url : iamgeList) {
            try {
                //3、将阿里云图片封装成要检测的内容
                JSONObject task = new JSONObject();
                task.put("dataId", UUID.randomUUID().toString());
                task.put("url", url);
                task.put("time", new Date());
                taskList.add(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return verify(taskList, client);
    }

    /***
     * 图片检测
     * 该方法需要传入图片字节数组集合
     * @throws Exception
     */
    public Map<String, String> imageGreenScanForStream(List<byte[]> iamgeList) {
        //1、client创建
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-shanghai",
                aliyunProperties.getAccessKey(),
                aliyunProperties.getSecret());
        DefaultProfile.addEndpoint("cn-shanghai", "Green", "green.cn-shanghai.aliyuncs.com");
        IAcsClient client = new DefaultAcsClient(profile);

        //2、将本地图片上传至阿里云
        List<JSONObject> taskList = new ArrayList<>();
        for (byte[] bytes : iamgeList) {
            ClientUploader clientUploader = ClientUploader.getImageClientUploader(profile, false);
            try {
                //3、 上传到服务端。
                String url = clientUploader.uploadBytes(bytes);
                //4、将阿里云图片封装成要检测的内容
                JSONObject task = new JSONObject();
                task.put("dataId", UUID.randomUUID().toString());
                task.put("url", url);
                task.put("time", new Date());
                taskList.add(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return verify(taskList, client);
    }

    /***
     * 图片检测
     * @param taskList
     * @return
     */
    public Map<String, String> verify(List<JSONObject> taskList, IAcsClient client) {
        //1、远程请求属性封装
        ImageSyncScanRequest imageSyncScanRequest = new ImageSyncScanRequest();
        imageSyncScanRequest.setAcceptFormat(FormatType.JSON);  // 指定API返回格式。
        imageSyncScanRequest.setMethod(MethodType.POST);  // 指定请求方法。
        imageSyncScanRequest.setEncoding("utf-8");
        imageSyncScanRequest.setProtocol(ProtocolType.HTTP);  // 支持HTTP和HTTPS。

        JSONObject httpBody = new JSONObject();
        //2、检测的场景
        httpBody.put("scenes", aliyunProperties.getScenes());
        httpBody.put("tasks", taskList);

        imageSyncScanRequest.setHttpContent(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(httpBody.toJSONString()),
                "UTF-8", FormatType.JSON);

        //3、超时设置
        imageSyncScanRequest.setConnectTimeout(3000);
        imageSyncScanRequest.setReadTimeout(10000);

        //4、上传图片
        HttpResponse httpResponse = null;
        try {
            httpResponse = client.doAction(imageSyncScanRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Map<String, String> resultMap = new HashMap<>();
        //5、 服务端接收到请求，完成处理后返回的结果。
        if (httpResponse != null && httpResponse.isSuccess()) {
            JSONObject scrResponse = JSON.parseObject(org.apache.commons.codec.binary.StringUtils.newStringUtf8(httpResponse.getHttpContent()));
            int requestCode = scrResponse.getIntValue("code");
            // 每一张图片的检测结果。
            JSONArray taskResults = scrResponse.getJSONArray("data");
            if (200 == requestCode) {
                for (Object taskResult : taskResults) {
                    // 单张图片的处理结果。
                    int taskCode = ((JSONObject) taskResult).getIntValue("code");
                    // 图片对应检测场景的处理结果。如果是多个场景，则会有每个场景的结果。
                    JSONArray sceneResults = ((JSONObject) taskResult).getJSONArray("results");
                    if (200 == taskCode) {
                        for (Object sceneResult : sceneResults) {
                            //检测结果
                            String suggestion = ((JSONObject) sceneResult).getString("suggestion");

                            //只记录审核未通过的数据
                            if (!Objects.equals("pass", suggestion)) {
                                String label = ((JSONObject) sceneResult).getString("label");//label违规类型
                                String scene = ((JSONObject) sceneResult).getString("scene");//解析结果
                                resultMap.put("suggestion", suggestion);
                                resultMap.put("label", label);
                                resultMap.put("scene", scene);
                            }
                        }
                    } else {
                        // 单张图片处理失败，原因视具体的情况详细分析。
                        throw new RuntimeException("内容加测失败！");
                    }
                }
            } else {
                throw new RuntimeException("图片检测失败！");
            }
        }
        //6、没有抛出异常，且没有检测结果，就是审核通过
        if (resultMap.size() == 0) {
            resultMap.put("suggestion", "pass");
        }
        return resultMap;
    }
}
